package thread.forkjoin;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RecursiveTask;

/**
 * @program: Multhread
 * @description: 这个是任务拆分和合并
 * @author: zhanghz001
 * @create: 2021-03-05 11:09
 **/
@Slf4j
public class SubTask extends RecursiveTask<Integer> {
    private static final int MAX = 100;
    private Integer start;
    private Integer end;
    
    public SubTask(Integer start, Integer end) {
        this.start = start;
        this.end = end;
    }
    
    @Override
    protected Integer compute() {
        if (end - start < MAX) {
            //小于边界，开始计算
            log.info("start = " + start + ";end = " + end);
            int total = 0;
            for (int i = start; i <= end; i++) {
                total += i;
            }
            return total;
        } else {
            //否则,需要劈开继续拆分
            SubTask task1 = new SubTask(start, (start + end) / 2);
            task1.fork();
            SubTask task2 = new SubTask((start + end) / 2 + 1, end);
            task2.fork();
            return task1.join() + task2.join();
        }
    }
}
